package com.fxz.bean.factory.registory.support;

import com.fxz.bean.factory.registory.SingletonBeanRegistry;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * 管理单实例Bean实例
 *
 * @author Fxz
 * @version 1.0
 * @date 2021-08-12 15:14
 */
public class DefaultSingletonBeanRegistry implements SingletonBeanRegistry {

    /**
     * 缓存
     */
    private Map<String, Object> singletons = new HashMap<>();

    /**
     * 通过名称获取单实例bean
     *
     * @param name
     * @return
     */
    @Override
    public Object getSingleton(String name) {
        return singletons.get(name);
    }

    /**
     * 通过Class获取单实例bean
     *
     * @param className
     * @return
     */
    @Override
    public String getSingleton(Class className) {
        Set<String> strings = singletons.keySet();
        for (String string : strings) {
            Object o = singletons.get(string);
            if (o.getClass() == className) {
                return string;
            }
        }
        return null;
    }

    /**
     * 注册
     *
     * @param name
     * @param bean
     */
    @Override
    public void registrySingleton(String name, Object bean) {
        singletons.put(name, bean);
    }
}
